<template>
	<view class="add-address-wrapper">
		<custom-header-bar title="新增地址" bg="1" backStatus="1"></custom-header-bar>
		<div class="content-box">
			<div class="form-wrapper">
				<u--form class="form-wrapper" labelPosition="left" labelAlign="left" labelWidth="180" :model="userInfo"
					:rules="rulesUserinfo" ref="formUserInfo">
					<!-- <view class="selectAddress" @click="clickUniMap">
						选择收货地址
					</view> -->
					<u-form-item borderBottom required label="姓名" label-width="150" prop="name">
						<u--input v-model="userInfo.name" clearable placeholder="请输入" />
					</u-form-item>
					<u-form-item borderBottom required label="电话" label-width="150" prop="mobile">
						<u--input v-model="userInfo.mobile" type="number" maxlength="11" placeholder="请输入" />
					</u-form-item>
					<u-form-item borderBottom required label="住址" label-width="150" prop="___path" @click="showPicker">
						<u--input disabled v-model="userInfo.___path" type="select" placeholder="请选择所在地区" />
						<u-icon color="#999999" size="28" slot="right" name="arrow-down"></u-icon>
					</u-form-item>
					<u-form-item borderBottom required class="detailAddress" label="详细地址" label-width="150"
						prop="addressDetail">
						<u--input type="textarea" v-model="userInfo.addressDetail" maxlength="100" height="150"
							placeholder="街道楼牌号等" />
					</u-form-item>
					<div class="save-button">
						<button type="default" class="button" @click="save">
							保存
						</button>
					</div>
				</u--form>
			</div>
			<m-city :provinceData="list" headTitle="区域选择" ref="cityPicker" @funcValue="getpickerParentValue"
				pickerSize="4">
			</m-city>

			<uniMap v-if="mapFlage" @close="closeMap" @callback="callBackAddress" />
		</div>
	</view>
</template>
<script>
	import {
		addAddress,
		editAddress,
		getAddressDetail,
		getdiqu
	} from "@/api/address.js";
	import gkcity from "@/components/m-city/m-city.vue";
	import uniMap from "./uniMap";
	import permision from "@/js_sdk/wa-permission/permission.js";
	import CustomHeaderBar from "@/components/custom-header-bar.vue"
	export default {
		components: {
			CustomHeaderBar,
			"m-city": gkcity,
			uniMap,
		},
		onShow() {
			// 判断当前系统权限定位是否开启
		},
		mounted() {},
		data() {
			return {
				lightColor: this.$lightColor, //高亮颜色
				mapFlage: false, // 地图选择开
				userInfo: {
					addressDetail: "", //地址详情
					name: "", //收货人姓名
					mobile: "", //手机号码
					addressList: [], //地址id
					addressStrList: [], //地址名字
					___path: "", //所在区域
					isDefault: false, //是否默认地址
				},
				// 表单提交校验规则
				rulesUserinfo: {
					name: [{
						required: true,
						message: "姓名不能为空",
						trigger: ["blur", "change"],
					}, ],
					mobile: [{
							required: true,
							message: "电话不能为空",
							trigger: ["blur", "change"],
						},
						{
							pattern: /^0?(13[0-9]|14[0-9]|15[0-9]|16[0-9]|17[0-9]|18[0-9]|19[0-9])[0-9]{8}$/,
							// 正则检验前先将值转为字符串
							transform(value) {
								return String(value);
							},
							message: '电话格式不正确',
							trigger: ['blur', 'change'],
						},
					],
					___path: [{
						required: true,
						message: "请选择所在区域",
						trigger: ["change"],
					}, ],
					addressDetail: [{
						required: true,
						message: "请填写详细地址",
						trigger: ["blur", "change"],
					}, ],
				},
				list: [{
					id: "",
					localName: "请选择",
					children: [],
				}, ],
			};
		},
		onLoad(option) {
			if (option.id) {
				getAddressDetail(option.id).then((res) => {
					const params = res.data.data;
					params.___path = params.addressOneStr + ' ' + params.addressTwoStr + ' ' + params
						.addressThreeStr + ' ' + params.addressFourStr;
					this.$set(this, "userInfo", params);
				});
			}
		},
		// 初始化rules必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {

		},
		methods: {
			// 关闭地图
			closeMap() {
				this.mapFlage = false;
			},
			// 打开地图并访问权限
			clickUniMap() {
				// #ifdef APP-PLUS
				if (plus.os.name == "iOS") {
					// ios系统
					permision.judgeIosPermission("location") ?
						(this.mapFlage = true) :
						this.refuseMapOuther();
				} else {
					// 安卓
					this.requestAndroidPermission(
						"android.permission.ACCESS_FINE_LOCATION"
					);
				}
				// #endif

				// #ifndef APP-PLUS
				this.mapFlage = true;
				// #endif
			},

			// 如果拒绝权限 提示区设置
			refuseMapOuther() {
				uni.showModal({
					title: "温馨提示",
					content: "您已拒绝定位,请开启",
					confirmText: "去设置",
					success(res) {
						if (res.confirm) {
							//打开授权设置
							// #ifndef MP-WEIXIN
							uni.getSystemInfo({
								success(res) {
									if (res.platform == "ios") {
										//IOS
										plus.runtime.openURL("app-settings://");
									} else if (res.platform == "android") {
										//安卓
										let main = plus.android.runtimeMainActivity();
										let Intent = plus.android.importClass(
											"android.content.Intent"
										);
										let mIntent = new Intent("android.settings.ACTION_SETTINGS");
										main.startActivity(mIntent);
									}
								},
							});
							// #endif
						}
					},
				});
			},

			// 获取安卓是否拥有地址权限
			async requestAndroidPermission(permisionID) {
				var result = await permision.requestAndroidPermission(permisionID);

				if (result == 1) {
					this.mapFlage = true;
				} else {
					this.refuseMapOuther();
				}
			},

			// 选择地址后数据的回调
			callBackAddress(val) {
				uni.showLoading({
					title: "加载中",
				});

				if (val.regeocodeData && val) {
					let address = val.regeocodeData;
					this.userInfo.addressDetail = address.formatted_address; //地址详情
					this.userInfo.___path = val.data.result.name;
					this.userInfo.addressList = val.data.result.id; // 地址id分割
					this.userInfo.addressStrList = val.data.result.name; //地址名称， '，'分割
					this.userInfo.lat = val.latitude; //纬度
					this.userInfo.lon = val.longitude; //经度
					uni.hideLoading();
				}

				this.mapFlage = !this.mapFlage; //关闭地图
			},

			// 保存当前 地址
			save() {
				this.$refs.formUserInfo.validate().then((res) => {
					let pages = getCurrentPages(); //获取页面栈
					let url = ''
					let beforePage = pages[pages.length - 2]	//上个页面
					url = '/' + beforePage.route
					let options = beforePage.options
					if(JSON.stringify(options) !== '{}') {
						url += '?'
					}
					for (let key in options) {
						const value = options[key]
						url += `${key}=${value}&`
					}
					// 如果没有id则为新增地址
					if (!this.userInfo.id) {
						// 删除没有的数据
						delete this.userInfo.___pathxxxxxxx;
						addAddress(this.userInfo).then((res) => {
							uni.navigateBack();
						});
					} else {
						// 修改地址
						delete this.userInfo.___path;
						delete this.userInfo.updateBy;
						delete this.userInfo.updateTime;
						console.log(url)
						editAddress(this.userInfo).then((res) => {
							// uni.redirectTo({
							// 	url: url,
							// });
							uni.navigateBack();
						});
					}
				});
			},

			// 三级地址联动回调
			getpickerParentValue(e) {
				// 将需要绑定的地址设置为空，并赋值
				this.userInfo.addressList = [];
				this.userInfo.addressStrList = [];
				let name = "";

				e.forEach((item, index) => {
					if (item.id) {
						// 遍历数据
						this.userInfo.addressList.push(item.id);
						this.userInfo.addressStrList.push(item.localName);
						name += item.localName;
						this.userInfo.___path = name;
					}
					if (index == e.length - 1) {
						//如果是最后一个
						let _town = item.children.filter((_child) => {
							return _child.id == item.id;
						});

						this.userInfo.lat = _town[0].center.split(",")[1];
						this.userInfo.lon = _town[0].center.split(",")[0];
					}
				});
			},

			// 显示三级地址联动
			showPicker() {
				this.$refs.cityPicker.show();
			},
		},

	};
</script>
<style scoped lang="scss">
	/deep/ .u-input {
		background-color: transparent !important;
	}

	.add-address-wrapper {
		height: 100%;
		padding: 160upx 0 0upx 0;
		box-sizing: border-box;
		background-color: #F4f4f4;

		.content-box {
			padding: 24upx;

			.form-wrapper {
				padding: 24upx 24upx 24upx 48upx;
				background-color: #ffffff;
				border-radius: 20upx;

				.arrow {
					height: 18upx;
				}
			}
		}

		.save-button {
			margin-top: 200upx;
			align-items: center;
			justify-content: center;
			height: 140rpx;

			.u-icon {
				margin-right: 16rpx;
			}

			.button {
				height: 80upx;
				line-height: 80upx;
				width: 300upx;
				display: flex;
				align-items: center;
				justify-content: center;
				background: #80D7CE;
				border-radius: 10upx;
				color: #ffffff;
			}
		}
	}
</style>
